package org.ytor.core.sysapi.dynamicsql.api;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.ytor.common.anno.AutoLog;
import org.ytor.common.exception.BaseException;
import org.ytor.common.model.R;
import org.ytor.common.util.Strs;
import org.ytor.common.util.bean.Beans;
import org.ytor.core.BaseController;
import org.ytor.core.querygen.WhereGenerator;
import org.ytor.core.sqlflow.Page;
import org.ytor.core.sqlflow.builder.support.WhereBuilder;
import org.ytor.core.sysapi.dynamicsql.logic.DynamicSqlConfigLogic;
import org.ytor.core.sysapi.dynamicsql.model.DynamicSqlConfig;
import org.ytor.core.sysapi.dynamicsql.repository.DynamicSqlConfigRepository;
import org.ytor.core.sysapi.dynamicsql.req.DynamicSqlConfigReq;
import org.ytor.core.sysapi.dynamicsql.resp.DynamicSqlConfigResp;
import org.ytor.core.sysapi.dynamicsql.resp.DynamicSqlExecResp;
import org.ytor.core.util.Pages;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * created by   on 2025年5月22日 13:10:52
 * <br/>
 * DynamicSqlConfig表控制器
 * <br/>
 */
@RestController
@RequestMapping("/sys/dynamicSql")
@Tag(name = "动态sql")
public class DynamicSqlConfigController extends BaseController<DynamicSqlConfig, DynamicSqlConfigLogic, DynamicSqlConfigRepository> {

    /**
     * 分页查询
     */
    @GetMapping("/page")
    @Operation(summary = "分页查询", description = "根据id查询对应的实体数据数据")
    public R<Page<DynamicSqlConfigResp>> page(@ParameterObject DynamicSqlConfigReq dynamicSqlConfigdata,
                                              @RequestParam(defaultValue = "1") Long pageNo,
                                              @RequestParam(defaultValue = "10") Long pageSize) {
        WhereBuilder where = WhereGenerator.where();
        Page<DynamicSqlConfig> page = repository.queryPage(where);
        return R.success((Pages.transPage(page, DynamicSqlConfig::toResp)));
    }

    /**
     * 根据id查询数据
     */
    @GetMapping("/queryById")
    @Operation(summary = "根据id查询", description = "根据id查询数据")
    protected R<DynamicSqlConfigResp> queryById(String id) {
        DynamicSqlConfig dynamicSqlConfig = repository.queryById(id);
        return R.success(dynamicSqlConfig.toResp());
    }

    /**
     * 新增或编辑数据
     */
    @PostMapping("/addOrUpdate")
    @Operation(summary = "新增或编辑", description = "根据有无主键id,新增或编辑数据")
    protected R<String> addOrUpdate(@RequestBody DynamicSqlConfigReq dynamicSqlConfigdata) {
        DynamicSqlConfig dynamicSqlConfig = Beans.copyProperties(dynamicSqlConfigdata, DynamicSqlConfig.class);
        repository.insertOrUpdate(dynamicSqlConfig);
        return R.success(dynamicSqlConfigdata.getId() == null ? "新增成功" : "编辑成功");
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete")
    @Operation(summary = "删除", description = "根据id删除数据")
    protected R<String> delete(@Parameter(description = "主键id") String ids) {
        if (Strs.isEmpty(ids)) {
            throw new BaseException("删除接口的ids不能为空");
        }
        List<String> idList = Arrays.asList(ids.split(","));
        repository.deleteById(idList);
        return R.success("删除成功");
    }

    /**
     * 新增或编辑数据
     */
    @AutoLog("执行动态sql")
    @PostMapping("/executeQuery")
    @Operation(summary = "执行动态sql", description = "执行动态sql")
    protected DynamicSqlExecResp executeQuery(@RequestParam String id, @RequestBody Map<String, Object> params) {
        return logic.execute(id, params);
    }

    /**
     * 动态执行GET接口
     */
    @GetMapping("/{apiPath}")
    public Object executeQueryForGet(@PathVariable("apiPath") String apiPath,
                                     @RequestParam Map<String, Object> params) {
        if (!apiPath.matches("^[a-zA-Z0-9_-]+$")) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("非法接口路径");
        }

        String fullPath = "/sys/dynamicSql/" + apiPath;
        DynamicSqlConfig dynamicSqlConfig = repository.select().where(w -> w.eq(DynamicSqlConfig::getApiPath, fullPath)
                        .eq(DynamicSqlConfig::getApiMethod, "GET")
                        .eq(DynamicSqlConfig::getStatus, 1))
                .limit(1)
                .one(DynamicSqlConfig.class);

        if (dynamicSqlConfig == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("接口不存在：" + fullPath);
        }
        return logic.execute(dynamicSqlConfig.getId(), params);
    }


    /**
     * 动态执行POST接口
     */
    @PostMapping("/{apiPath}")
    public Object executeQueryForPost(@PathVariable("apiPath") String apiPath,
                                      @RequestBody Map<String, Object> params) {
        if (!apiPath.matches("^[a-zA-Z0-9_-]+$")) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("非法接口路径");
        }

        String fullPath = "/sys/dynamicSql/" + apiPath;
        DynamicSqlConfig dynamicSqlConfig = repository.select().where(w -> w
                        .eq(DynamicSqlConfig::getApiPath, fullPath)
                        .eq(DynamicSqlConfig::getApiMethod, "POST")
                        .eq(DynamicSqlConfig::getStatus, 1))
                .limit(1)
                .one(DynamicSqlConfig.class);

        if (dynamicSqlConfig == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("接口不存在：" + fullPath);
        }
        return logic.execute(dynamicSqlConfig.getId(), params);
    }


}